<?php

namespace app\api\controller\resell;

use app\api\BaseController;
use app\store\service\GroupActivityService;
use think\facade\Db;
use WeChat\Contracts\Tools;

class TradeController extends BaseController
{
    /**
     * 微信回调
     * */
    public function wxNotify()
    {
        $result = Tools::xml2arr(file_get_contents('php://input'));
        if (!empty($result)){
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                $this->changeTrade($result['out_trade_no'],$result['time_end']);
                echo Tools::arr2xml(['return_code' => 'SUCCESS', 'return_msg' => 'OK']);
            }
        }

    }

    /**
     * 支付宝回调
     * */
    public function aliNotify()
    {
        $post =  $_POST;
        if(!empty($post)){
            if ($post['trade_status'] == 'TRADE_SUCCESS'){
                $this->changeTrade($post['out_trade_no'],$post['gmt_payment']);
                echo 'success';
            }
        }
    }


    public function changeTrade($out_trade_no,$time_end)
    {

        $groupOrder = Db::name('group_order_trade')
            ->alias('a')
            ->field('a.group_order_id,b.store_id,b.prepayment_amount,a.trade_fee')
            ->join('group_order b','a.group_order_id=b.id')
            ->where('a.out_trade_no',$out_trade_no)
            ->find();


        Db::name('group_order_trade')
            ->where('out_trade_no',$out_trade_no)
            ->update([
                'trade_status' => 1,
                'trade_time' => strtotime($time_end)
            ]);

        Db::name('group_order')->where('id',$groupOrder['group_order_id'])->update(['status' => 3]);


        $group_activity = Db::name('group_activity_record')
                            ->field('resell_session_id,group_num')
                            ->where('group_order_id',$groupOrder['group_order_id'])
                            ->find();

        if (!empty($group_activity)){
            $group_num = Db::name('group_activity_record')
                ->alias('a')
                ->join('group_order_trade b','a.group_order_id=b.group_order_id')
                ->where([
                    'a.resell_session_id' => $group_activity['resell_session_id'],
                    'b.trade_status' => 1,
                ])->count('a.id');
            if ($group_num==$group_activity['group_num']){

                $records  = $this->getActivityRecord($group_activity['resell_session_id']);

                $index = array_rand($records);
                $user_id = $records[$index]['user_id'];
                unset($records[$index]);
                $ids = array_column($records,'user_id');

                Db::name('group_activity_record')
                    ->where(['resell_session_id' => $group_activity['resell_session_id'],'user_id' => $user_id])
                    ->update(['status' => 2]);

                /**
                 * 失败处理
                 * */
                Db::name('group_activity_record')
                    ->where('resell_session_id',$group_activity['resell_session_id'])
                    ->whereIn('user_id',$ids)
                    ->update(['status' => -1]);

                GroupActivityService::saveFailRefundQueue($groupOrder['store_id'],$records);

                Db::name('user_resell_session')->where('resell_session_id',$group_activity['resell_session_id'])->update([
                    'status' => 2,
                    'resell_status' => 1
                ]);
            }
        }

    }

    /**
     * 获取转售记录信息
     * */
    protected function getActivityRecord($resell_session_id)
    {
        $records = Db::name('group_activity_record')
            ->field('a.user_id,a.group_order_id,b.trade_method,b.trade_fee,b.out_trade_no')
            ->alias('a')
            ->join('group_order_trade b','a.group_order_id=b.group_order_id')
            ->where([
                'a.resell_session_id' => $resell_session_id,
                'b.trade_status' => 1,
            ])->select();

        if ($records->isEmpty()){
            return [];
        }

        return $records->toArray();
    }



}